<template>
  <el-container>
    <el-aside :width="isCollapse ? '64px' : '240px'">
      <div class="logo-box">
        <img src="@/assets/logo/logo.png" class="logo-img" />
      </div>
      <div class="menu-scroll">
        <el-menu @select="handleSelect" :default-active="activeTab" :collapse="isCollapse" class="aside-vertical-menu">
          <template v-for="(topMenu, index) in topMenuList" :key="topMenu.name">
            <el-sub-menu v-if="topMenu.children?.length" :index="topMenu.name">
              <template #title>
                <el-icon>
                  <component :is="topMenu.meta.icon" />
                </el-icon>
                <span>{{ topMenu.meta.title }}</span>
              </template>
              <el-menu-item v-for="child in topMenu.children" :key="child.name" :index="child.name">
                <el-icon>
                  <component :is="child.meta.icon" />
                </el-icon>
                <span>{{ child.meta.title }}</span>
              </el-menu-item>
            </el-sub-menu>
            <el-menu-item v-else :index="topMenu.name">
              <el-icon>
                <component :is="topMenu.meta.icon" />
              </el-icon>
              <span>{{ topMenu.meta.title }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </div>
    </el-aside>

    <el-container>
      <el-header>
        <el-row class="header-content">
          <el-col :span="2">
            <el-button @click="toggleAside">
              <el-icon color="rgb(56,18,110)" size="large">
                <component :is="toggleIcon" />
              </el-icon>
            </el-button>
          </el-col>
          <el-col :span="22" style="text-align: right;">
            <!-- 智能分析助手入口图标 -->
            <el-tooltip content="智能分析助手" placement="bottom">
              <el-button
                circle
                size="large"
                style="margin-right: 18px;"
                @click="showAssistant = true"
              >
                <el-icon><MagicStick /></el-icon>
              </el-button>
            </el-tooltip>
            <!-- 个人信息下拉 -->
            <el-dropdown>
              <span class="el-dropdown-link">
                <span>你好,</span>
                <span style="margin:0 10px;">{{ userInfo.username }}</span>
                <el-avatar :size="60" :src="userInfo.avatar" />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="modifyPwd">修改密码</el-dropdown-item>
                  <el-dropdown-item @click="showInfo">个人资料</el-dropdown-item>
                  <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
        </el-row>
      </el-header>

      <el-main>
        <el-tabs v-model="currentActiveTab" @tab-click="handleTabClick" type="card" closable
          @tab-remove="handleTabRemove">
          <el-tab-pane v-for="tab in tabs" :key="tab.name" :label="tab.title" :name="tab.name">
            <router-view v-if="activeTab === tab.name" />
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>

    <el-drawer
      v-model="showAssistant"
      title="智能分析助手"
      direction="rtl"
      size="420px"
      :with-header="true"
      :close-on-click-modal="false"
    >
      <SmartAssistant mode="drawer" />
    </el-drawer>
  </el-container>
</template>

<script setup>
import { ref, computed, watch, onMounted, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useTabsStore } from '@/store/tabs.js'
import SmartAssistant from '@/views/assistant/SmartAssistant.vue'
import { MagicStick } from '@element-plus/icons-vue'

const isCollapse = ref(false)
const toggleIcon = ref('Fold')
const tabsStore = useTabsStore()
const router = useRouter()
const route = useRoute()
const currentActiveTab = ref(tabsStore.activeTab)

const topMenuList = computed(() => router.getRoutes().filter(r => r.meta?.top))
const activeTab = computed(() => tabsStore.activeTab)
const tabs = computed(() => tabsStore.tabs)

const handleSelect = (index) => {
  const menuRoute = topMenuList.value.find(r => r.name === index || r.children?.some(child => child.name === index))
  const childRoute = menuRoute?.children?.find(child => child.name === index)
  const selectedRoute = childRoute || menuRoute
  if (selectedRoute?.meta) {
    tabsStore.addTab({ title: selectedRoute.meta.title, name: selectedRoute.name })
    router.push({ name: selectedRoute.name })
  }
}

const toggleAside = () => {
  isCollapse.value = !isCollapse.value
  toggleIcon.value = isCollapse.value ? 'Expand' : 'Fold'
}

const handleTabClick = (tab) => {
  tabsStore.setActiveTab(tab.props.name)
  router.push({ name: tab.props.name })
}

const handleTabRemove = (tabName) => {
  tabsStore.closeTab(tabName)
}

watch(tabs, (newTabs) => {
  localStorage.setItem('tabs', JSON.stringify(newTabs))
}, { deep: true })

watch(activeTab, (newActiveTab) => {
  localStorage.setItem('activeTab', newActiveTab)
  currentActiveTab.value = newActiveTab
})

watch(isCollapse, (newIsCollapse) => {
  localStorage.setItem('isCollapse', newIsCollapse)
})

onMounted(() => {
  isCollapse.value = localStorage.getItem('isCollapse') === 'true'
  const savedTabs = JSON.parse(localStorage.getItem('tabs'))
  const savedActiveTab = localStorage.getItem('activeTab')
  if (savedTabs) savedTabs.forEach(tab => tabsStore.addTab(tab))
  if (savedActiveTab) {
    tabsStore.setActiveTab(savedActiveTab)
    currentActiveTab.value = savedActiveTab
    router.push({ name: savedActiveTab })
  }
})

const userInfo = reactive({
  avatar: '/src/assets/img/profile.jpg',
  username: '管理员'
})

const showInfo = () => {
  tabsStore.addTab({ name: 'Info', title: '个人信息' })
  router.push({ name: 'Info' })
}

const modifyPwd = () => {
  tabsStore.addTab({ name: 'ModifyPwd', title: '修改密码' })
  router.push({ name: 'ModifyPwd' })
}

const logout = () => {
  router.push('/login')
}

const showAssistant = ref(false)
</script>

<style scoped>
.logo-box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 70px;
  background-image: linear-gradient(to top, #fff1eb 0%, #ace0f9 100%);
  /* 保证 logo 固定在顶部 */
  position: sticky;
  top: 0;
  z-index: 2;
}

.logo-img {
  width: 100px;
  height: 140px;
  object-fit: contain;
}

.el-header {
  background-image: linear-gradient(to top, #fff1eb 0%, #ace0f9 100%);
  color: #333;
  text-align: left;
  line-height: 60px;
  height: 70px;
}

.custom-aside {
  transition: width 0.3s;
}

.custom-aside .el-menu,
.custom-aside.is-collapse .el-menu {
  background-color: #fff;
}

.custom-aside .el-menu-item {
  color: rgb(56, 18, 110);
}

.custom-aside .el-menu-item:hover {
  background-color: #409eff;
  color: #fff;
}

.custom-aside .el-sub-menu__title {
  color: #c0c4cc;
}

.custom-aside .el-sub-menu__title:hover {
  background-color: #409eff;
  color: #fff;
}

.aside-vertical-menu:not(.el-menu--collapse) {
  width: 235px;
  min-height: 100vh;
  border-color: transparent;
}

.el-aside::-webkit-scrollbar {
  display: none;
}

.el-container {
  height: 100vh;
}

.el-aside {
  background-color: #f2f2f2;
}

.aside-vertical-menu {
  padding: 25px 0 0 20px;
}

.el-menu-item,
:deep(.el-sub-menu__title) {
  font-size: 17px;
}

.el-sub-menu.is-opened .el-menu-item {
  font-size: 16px !important;
}

.el-main {
  padding: 20px 0 20px 20px;
  margin-top: 15px;
}

:deep(.el-tabs__item.is-active) {
  background-color: var(--el-color-primary) !important;
  color: #fff !important;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: bold;
}

.el-footer {
  height: 35px;
  text-align: right;
}

.el-dropdown-link {
  display: inline-flex;
  align-items: center;
  outline: none;
}

.el-dropdown-link:focus,
.el-dropdown-link:hover {
  outline: none !important;
  box-shadow: none !important;
}

.header-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.el-drawer__body {
  padding: 0 !important;
}

.menu-scroll {
  max-height: calc(100vh - 70px);
  overflow-y: auto;
  scrollbar-width: none; /* Firefox */
}

.menu-scroll::-webkit-scrollbar {
  display: none; /* Chrome/Safari/Edge */
}
</style>
